<template>
    <el-container style="height: 80vh" ref="bodyform">
        <div class="el_main_content">
            <div class="main_content_header">梦想起航</div>
            <div class="main_content_center">
                <el-scrollbar class="faultExpertConsultation_scrollbar" ref="scrollbarRef">
                    <div v-for="(item, index) in messagesWithTimestamps" :key="index"
                        v-show="messagesWithTimestamps.length > 0">

                        <div v-if="item.isSystem" class="system-message">
                            {{ item.text }} - {{ formatSendTime(item.timestamp) }}
                        </div>
                        <div class="question chat">
                            <div class="chat_question chat_common">
                                <span>{{ item.question }}</span>
                            </div>
                            <el-avatar class="avatar">
                                <span class="me">我</span>
                            </el-avatar>
                        </div>
                        <div class="answer chat" v-if="item.answer">
                            <el-avatar class="avatar">
                                <img src="../../../assets/images/avater.jpg" alt="">
                            </el-avatar>
                            <div class="chat_answer chat_common">
                                <span>{{ item.answer }}</span>
                            </div>
                        </div>
                    </div>
                </el-scrollbar>
            </div>
            <div class="main_content_footer">
                <div class="input_box">
                    <textarea class="chat-input no-border" v-model="question" @keydown.enter="askClick(question)" />
                </div>
                <div class="btn_box">
                    <el-button type="primary" class="btn" @click="askClick(question)">
                        发送
                    </el-button>
                </div>
            </div>
        </div>
    </el-container>
</template>

<script setup>
import { ref, nextTick, computed, watch, onMounted } from "vue";
import { ElMessage } from "element-plus";
import io from 'socket.io-client';
const socket = ref(null)
const user = ref(sessionStorage.getItem('user'))
onMounted(() => {

    socket.value = new WebSocket(`ws://localhost:8080?user=${String(user.value)}`);

    socket.value.addEventListener('open', () => {
        console.log('WebSocket连接已打开');
        alert('连接成功');
    });

    // 接收消息

    // socket.value.addEventListener('message', (event) => {
    //     try {
    //         const message = JSON.parse(event.data);
    //         // 找到最后一个没有answer的消息，更新它
    //         const lastMessageIndex = chatList.value.findLastIndex(item => !item.answer);
    //         // 区分发送者和接收者
    //         if (message.sender !== user.value) {
    //             const newMsg = {
    //                 question: message.text,
    //                 answer: null,
    //                 timestamp: new Date(),
    //                 sender: message.sender
    //             };

    //             chatList.value.push(newMsg);
    //         }
    //         localStorage.setItem('chatMessages', JSON.stringify(chatList.value));
    //     } catch (error) {
    //         console.error('解析消息时出错:', error);
    //     }

    // })
    // 消息处理
    socket.value.addEventListener('message', (event) => {
        try {
            const msg = JSON.parse(event.data);

            if (msg.type === 'message') {
                chatList.value.push({
                    sender: msg.sender,
                    question: msg.text,
                    answer: null,
                    timestamp: new Date(msg.timestamp),
                    isCurrentUser: msg.sender === user.value
                });
            } else if (msg.type === 'system') {
                // 系统消息（用户进出通知）
                chatList.value.push({
                    isSystem: true,
                    text: msg.text,
                    timestamp: new Date(msg.timestamp)
                });
            }

            saveMessages();
        } catch (error) {
            console.error('解析消息时出错:', error);
        }
    });
    // 从 localStorage 加载历史消息
    const storedMessages = localStorage.getItem('chatMessages');
    if (storedMessages) {
        chatList.value = JSON.parse(storedMessages);
    }
})

// //发送消息
// const askClick = (val) => {
//     if (val !== "") {
//         const newMessage = {
//             question: val,
//             answer: null, // 初始化为null，等待服务器响应
//             timestamp: new Date(),
//             sender: user.value,
//             receiver: user.value === '段红运' ? '段红运' : '焦凯航'
//         };
//         chatList.value.push(newMessage);
//         socket.value.send(JSON.stringify(val));
//         question.value = "";
//     } else {
//         ElMessage("不能发送空白消息");
//     }
// };
const askClick = (val) => {
    if (val !== "") {
        const newMessage = {
            text: val,  // 改为text字段（与后端匹配）
            sender: user.value,
            receiver: user.value === '段红运' ? '焦凯航' : '段红运' // 修正逻辑
        };

        chatList.value.push({
            question: val,
            answer: null,
            timestamp: new Date(),
            sender: user.value
        });

        socket.value.send(JSON.stringify(newMessage)); // 发送完整对象
        question.value = "";
    }
};


// const socket = io('http://localhost:3000'); // 确保连接到正确的端口
const question = ref(""); // 输入框值
const chatList = ref([]); // 循环的聊天数组
const scrollbarRef = ref(null);
// // 创建新的对话数组，加上属性showTime
const messagesWithTimestamps = computed(() => {
    return chatList.value.map((item, index) => ({

        ...item,
        showTime: index === 0 || shouldShowTime(index),
    }));
});

// 计算两次会话时间是否超过3分钟
const shouldShowTime = (index) => {
    const current = new Date(chatList.value[index - 1].timestamp);
    const next = new Date(chatList.value[index].timestamp);
    const diff = next ? next - current : 0;
    return diff > 3 * 60 * 1000; // 如果间隔超过3分钟返回true
};


// 滚动事件到底部事件
const scrollToBottom = () => {
    nextTick(() => {
        let chat = document.querySelector(".main_content_center");
        scrollbarRef.value.wrapRef.scrollTop = chat.scrollHeight;
    });
};

watch(chatList, (newVal) => {
    scrollToBottom();
}, { immediate: true });

// 时间格式化
const formatSendTime = (sendTime) => {
    const now = new Date();
    const sendDate = new Date(sendTime);
    const timeDiff = now - sendDate;
    const oneDay = 24 * 60 * 60 * 1000;

    if (timeDiff < 0) {
        return "Invalid time"; // 或者其他错误处理
    }
    if (timeDiff < oneDay) {
        return "今天 " + formatTime(sendDate);
    }
    return sendDate.toLocaleDateString("zh-CN") + " " + formatTime(sendDate);
};

const formatTime = (date) => {
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return hours + ":" + minutes;
};
</script>

<style>
.no-border {
    border: none;
    outline: none;
    resize: none;
}
</style>

<style lang="less" scoped>
.el_main_content {
    width: 50%;
    height: 70%;
    border-radius: 5px;
    border: 1px solid #e4e7ed;
    box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
    margin: auto;

    .main_content_header {
        width: 100%;
        height: 50px;
        border-radius: 5px;
        background-color: #7de0bd;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 16px;
    }

    .main_content_center {
        width: 100%;
        position: relative;
        height: calc(100% - 170px);
        margin: 10px 0px;

        .chat_time {
            display: flex;
            justify-content: center;
            font-size: 10px;
        }

        .question {
            display: flex;
            justify-content: flex-end;
        }

        .chat_question {
            background-color: #8ce45f;
            margin-right: 5px;
            color: #ffffff;
        }

        .chat_answer {
            background-color: #f2f3f5;
            margin-left: 5px;
        }

        .chat {
            width: 98%;
            margin: 10px auto;
            display: flex;
        }

        .chat_common {
            font-size: 12px;
            max-width: 40%;
            padding: 10px;
            border-radius: 2px;
            word-break: break-all;
            display: flex;
            align-items: center;
        }

        .avatar {
            background-color: #409eff;

        }

        .me {
            font-size: 16px;
            color: #ffffff;
            font-weight: bold;
        }
    }

    .main_content_footer {
        width: 100%;
        height: 20px;
        border-top: 1px solid #e4e7ed;

        .input_box {
            width: 100%;
            height: 60px;

            .chat-input {
                width: calc(100% - 80px);
                padding: 10px;
                margin: auto;
            }
        }

        .btn_box {
            width: 100%;
            height: 40px;
            margin-top: -50px;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            .btn {
                margin-right: 10px;
            }
        }
    }
}

.system-message {
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 12px;
    color: #ccc;
}
</style>
